<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//专著基本信息
class Monograph extends AdminController {

	function __construct() { 
		parent::__construct();
		$this -> load -> model("Monograph_model");
		$this->load->model("Monograph_kh_model");
		$this -> load -> model("File_model");
		$this -> load -> model("Subject_model");
		$this -> load -> model("Author_model");
		$this -> load -> model("Publisher_model");
        $this -> load -> model("User_model");
		$this->load->library('ProjectService/export_service');
		$this->load->library('ProjectService/audit_service');
        $this->load->library('ProjectService/upload_service');
		$this->load->library('ProjectService/check_service');
		$this -> sidebar = "Fruit";
	}

	public function Index() {
		$role=explode(',', getSess()['sub_role_id']);
		array_push($role, getSess()['role_id']);

		$data['is_add'] = 1;
		if(in_array(WebRole::BranchPresident[XPHEnum::Value], $role) || in_array(WebRole::BranchManage[XPHEnum::Value], $role) || in_array(WebRole::Sscientifictaff[XPHEnum::Value], $role)){
			$data['is_add'] = 0;
		}
		$this -> load -> view('admin/monographList',$data);
	}

	function getDatas($params = array(), $isExport = false) {
		$connar = array();
		$params = $_POST;
		if (!$isExport) {			
			$connar = $this -> Monograph_model -> pickPages($connar, $params);
		}

		$connar['orderby'] = "change_status desc,created desc";
		$connar['where']=$this->sqlEscape('is_del=?? ',array(CommonWhether::Not [XPHEnum::Value]));
		$connar['items']="db_monograph.*,author.author,(case when status = '".ResultState::UnSubmit[XPHEnum::Value]."' THEN 0 when status = '".ResultState::Auditing[XPHEnum::Value]."' THEN 1 when status = '".ResultState::Publiced[XPHEnum::Value]."' THEN 3 when status = '".ResultState::Fail[XPHEnum::Value]."' THEN 99 END ) as change_status";
		$connar['join']=array('(select group_concat(db_author.author_name  ORDER BY id ASC) author,data_id FROM db_author WHERE db_author.type = '.ResultsType::Second[XPHEnum::Value].'  GROUP BY db_author.data_id ) author','author.data_id=db_monograph.id');


		$role=explode(',', getSess()['sub_role_id']);
		array_push($role, getSess()['role_id']);

		$dept_name = getSess()['dept_name'];

		if(in_array(WebRole::BranchPresident[XPHEnum::Value], $role) || in_array(WebRole::BranchManage[XPHEnum::Value], $role)){
			$connar['where'] .= $this->sqlEscape(' and dept_name=?? and status >?? ',array($dept_name,ResultState::UnSubmit [XPHEnum::Value]));		
		}else if(in_array(WebRole::Sscientifictaff[XPHEnum::Value], $role)){
			$connar['where'] .= $this->sqlEscape('and status >?? ',array(ResultState::UnSubmit [XPHEnum::Value]));
		}else if(in_array(WebRole::Teacher[XPHEnum::Value], $role)){
			$connar['where'] .= $this->sqlEscape(' and (creator=?? ',array(getSess()['id']));
			 $connar['where'] .= " or author.author like '%" . getSess()['username'] . "%' )";
		}
		// if(in_array(WebRole::BranchPresident[XPHEnum::Value], $role) || in_array(WebRole::BranchManage[XPHEnum::Value], $role)){
		// 	$connar['where'] .= $this->sqlEscape(' and dept_name=?? ',array($dept_name));		
		// }else if(in_array(WebRole::Teacher[XPHEnum::Value], $role)){
		// 	$connar['where'] .= $this->sqlEscape(' and creator=?? ',array(getSess()['id']));
		// }

		if (isset($params['param'])) {
			$connar['where'] .= " and (name like '%" . $params['param'] . "%' )";
		}
		if(isset($params['audit_type']) && $params['audit_type']!='-1'){
            $connar['where'] .=$this->sqlEscape(" and is_submit_cg=??",array($params['audit_type']));
		}
		
		if (!$isExport) {
			$data = $this -> Monograph_model -> get_page_list($connar);
		} else {
			$data["ret"] = $this -> Monograph_model -> get_list_full($connar);
		}

		foreach ($data['ret'] as $k => $v) {
			$data['ret'][$k]['is_submit_cg_char'] = (new CommonWhether())->show($v['is_submit_cg']);
			if($v['status'] == ResultState::UnSubmit [XPHEnum::Value] || $v['status'] == ResultState::Fail [XPHEnum::Value]){
				$data['ret'][$k]['is_audit'] = true;
			}else{
				// $data['ret'][$k]['is_audit'] = false;
				if($v['status'] == ResultState::Auditing [XPHEnum::Value]){
                    $data['ret'][$k]['is_audit'] = false;
                }else{
                    if(in_array(WebRole::Admin[XPHEnum::Value], $role) || in_array(WebRole::Manage[XPHEnum::Value], $role)){
                        $data['ret'][$k]['is_audit'] = true;
                    }else{
                        $data['ret'][$k]['is_audit'] = false;
                    }                 
                }  
			}

			if($v['creator'] == getSess()['id']){
                $data['ret'][$k]['is_edit'] = true;
            }else{
                $data['ret'][$k]['is_edit'] = false;
            }

			$data['ret'][$k]['status_char'] = (new ResultState())->show($v['status']);
			// $data['ret'][$k]['is_submit_kh_char'] = (new CommonWhether())->show($v['is_submit_kh']);
			if($v['is_submit_kh'] == 0){
				$data['ret'][$k]['is_submit_kh_char'] = '未提交';
			}else{
				$data['ret'][$k]['is_submit_kh_char'] ='已提交';
			}
			$data['ret'][$k]['is_cooperation'] = (new CommonWhether())->show($v['is_cooperation']);
			$data['ret'][$k]['publish_time'] = $v['publish_time']?date('Y-m-d',$v['publish_time']):'--';
			$data['ret'][$k]['createdChar'] = $v['created']?date('Y-m-d H:i:s',$v['created']):'--';
		}
		if (!$isExport) {
			echo json_encode($data);
		} else {		
			//导出excel
			$new_list = array();	//需要导出的数据组
			foreach ($data["ret"] as $key => $value) {
				$new_list[$key]['xuhao'] = $key+1;//第一列序号
				$new_list[$key]['name'] = $value['name']; //著作名称
				$new_list[$key]['author'] = $value['author'];//所属作者
				$new_list[$key]['words_number'] = $value['words_number'];//总字数(千字)
				$new_list[$key]['school_words_number'] = $value['school_words_number'];//本校撰写字数(千字)
				$new_list[$key]['type'] = $value['type'];//著作类别
				$new_list[$key]['nature'] = $value['nature'];//著作性质				
				$new_list[$key]['publish_time'] = $value['publish_time'];//出版日期
				$new_list[$key]['publish_house'] = $value['publish_house'];//出版社
				$new_list[$key]['publish_house_level'] = $value['publish_house_level'];//出版社级别
				$new_list[$key]['publish_address'] = $value['publish_address'];//出版地			
				$new_list[$key]['isbn'] = $value['isbn'];//ISBN号
				$new_list[$key]['subject'] = $value['subject'];//学科门类
				$new_list[$key]['is_cooperation'] = $value['is_cooperation'];//是否合作完成
				$new_list[$key]['school_rank'] = $value['school_rank'];//本校排名
				$new_list[$key]['personal_rank'] = $value['personal_rank'];//个人排名
				$new_list[$key]['performance_score'] = $value['performance_score'];//业绩分
				$new_list[$key]['bonus'] = $value['bonus'];			//奖金
				$new_list[$key]['dept_name'] = $value['dept_name'];//所属单位
				$new_list[$key]['remark'] = $value['remark'];//备注
				$new_list[$key]['createdChar'] = $value['createdChar'];//创建时间
			}
			   //导出excel名称
				$name = '专著基本信息';

		        //导出表头名称
		        $tableth = '序号,著作名称,所属作者,总字数(千字),本校撰写字数(千字),著作类别,著作性质,出版日期,出版社,出版社级别,出版地,ISBN号,学科门类,是否合作完成,本校排名,个人排名,业绩分,奖金,所属单位,备注,创建时间';

		 	   //new_list导出数据列,title 导出表名称,tableth表头名称		

		       $desc =  $this->export_service->export_excel($new_list,$name,$tableth,2,3,$name);

		       //返回地址信息
		       $director = $desc['director'];$file_name = $desc['file_name'];     
		        exit(retJson('返回地址',true,$director.$file_name));
			
		}

		
	}


	function edit($id){

		//是否合作完成
		$typelist =	array();
		foreach ((new CommonWhether())->getAll() as $k => $v) {
				$typelist[$k]['Value'] = $v[XPHEnum::Value];
				$typelist[$k]['Caption'] = $v[XPHEnum::Caption];
		}
		$data['typelist'] = $typelist;

		//是否提交成果
		$is_submit_cg_arr =	array();
		foreach ((new CommonWhether())->getAll() as $k => $v) {
				$is_submit_cg_arr[$k]['Value'] = $v[XPHEnum::Value];
				$is_submit_cg_arr[$k]['Caption'] = $v[XPHEnum::Caption];
		}
		$data['is_submit_cg_arr'] = $is_submit_cg_arr;

		// $data['examine_level_arr'] = array('国家级','省级','市级','校级','分院级'); 
		//考核等级
		$examine_level_arr=array();
		foreach ((new examine_level())->getAll() as $k => $v) {
			$examine_level_arr[$v[XPHEnum::Value]] = $v[XPHEnum::Caption];
		}
		$data['examine_level_arr'] = $examine_level_arr;

		//刊物发行类型
		// $type_arr = '独著,合著';
		// $data['type_arr'] = explode(",", $type_arr);
		$type_arr=array();
		foreach ((new MonographType())->getAll() as $k => $v) {
			$type_arr[$v[XPHEnum::Value]] = $v[XPHEnum::Caption];
		}
		$data['type_arr'] = $type_arr;

		$data['nature_arr'] = array('A','B','C','其他');

		//学科门类
		$subject_arr = $this->Subject_model->get_list(array());
		$data['subject_arr'] = array_column($subject_arr, 'name');

		//教师/学生
		$data['subject']=$this->Subject_model->get_list(array());
		$identity_arr = array();
		foreach ((new CommonIdentity())->getAll() as $k => $v) {
			$identity_arr[$k]['Value'] = $v[XPHEnum::Value];
			$identity_arr[$k]['Caption'] = $v[XPHEnum::Caption];
		}
		$data['identity_arr'] = $identity_arr;

		$sex_arr = array();
		foreach ((new CommonGender())->getAll() as $k => $v) {
			$sex_arr[$k]['Value'] = $v[XPHEnum::Value];
			$sex_arr[$k]['Caption'] = $v[XPHEnum::Caption];
		}
		$data['sex_arr'] = $sex_arr;

			//出版社级别
		$publish_house_arr=array();
		foreach ((new PublisherLevel())->getAll() as $k => $v) {
			$publish_house_arr[$k]['Value'] = $v[XPHEnum::Value];
			$publish_house_arr[$k]['Caption'] = $v[XPHEnum::Caption];
		}
		$data['publish_house_arr'] = $publish_house_arr;

		
		$data['id'] = $id;
		
        
		if($id == 0){
			$data['title'] = "新增专著基本信息";
			$data['detail'] = $this -> Monograph_model -> get_single(array("id" => $id));
			$data['can_audit'] = CommonWhether::Not[XPHEnum::Value];
			$data['can_save']=CommonWhether::Whether[XPHEnum::Value];			
			$data['can_pass']=CommonWhether::Not[XPHEnum::Value];
			$data['can_refused']=CommonWhether::Not[XPHEnum::Value];
			$data['dept_name_arr']=(new addDept)->getAllOneD();

		}else{

			$data['title'] = "编辑专著基本信息";

			$data['detail'] = $this -> Monograph_model -> get_single(array("id" => $id));

			 //2024年5月30号之前取之前旧的部门
			if($data['detail']['created'] < 1716998400){
                $data['dept_name_arr']=(new Dept)->getAllOneD();
                foreach($data['dept_name_arr'] as $k=>$v){
                    if($v == '机械工程分院' || $v== '电气电子工程分院'){
                        unset($data['dept_name_arr'][$k]);
                    }
                }
            }else{
                $data['dept_name_arr']=(new addDept)->getAllOneD();
            }

			$data['detail']['publish_time'] = date("Y-m-d",$data['detail']['publish_time']);

			// 作者
			$connar['where']=$this->sqlEscape('db_author.data_id=?? and db_author.type=??  and db_user.is_del=0 ', array($id,ResultsType::Second[XPHEnum::Value]));
            $connar['items']="db_author.*,db_user.id as author_id,db_user.usercode,db_user.username";
            $connar['join']=array('db_user','db_user.id=db_author.author_id and db_user.username=db_author.author_name');
			$connar1['groupby'] = "db_author.author_id";
            $connar['orderby'] = "db_author.id ASC";
            $data['author']=$this->Author_model->get_list_full($connar);
			// $data['author']=$this->Author_model->get_list(array('data_id'=>$id,'type'=>ResultsType::Second[XPHEnum::Value]));
			/*$img = $this -> File_model -> get_single(array("data_id" => $data['detail']['id'],'type'=>ResultsType::Second[XPHEnum::Value],'file_type'=>FileType::Img[XPHEnum::Value]));
			$data['detail']['img'] = $img['src']?$img['src']:'';

			$files = $this -> File_model -> get_single(array("data_id" => $data['detail']['id'],'type'=>ResultsType::Second[XPHEnum::Value],'file_type'=>FileType::File[XPHEnum::Value]));
			$data['detail']['filename'] = $files['src']?$files['src']:'';
			$data['detail']['file_id'] = $files['id'];
			if($files['src']){
				$new_name = explode("/",$files['src']);
				$data['detail']['new_filename'] = substr($new_name[3],8);;
			}else{
				$data['detail']['new_filename'] = '';
			}*/

			$img = $this -> File_model -> get_list(array("data_id" => $data['detail']['id'],'type'=>ResultsType::Second[XPHEnum::Value],'file_type'=>FileType::Img[XPHEnum::Value]));
			$data['detail']['img'] = $img;

			$files = $this -> File_model -> get_list(array("data_id" => $data['detail']['id'],'type'=>ResultsType::Second[XPHEnum::Value],'file_type'=>FileType::File[XPHEnum::Value]));
			foreach ($files as $k => $v) {
				$files[$k]['filename']= substr(explode("/",$v['src'])[3],8);
			}
			$data['detail']['file']=$files;

			$role=explode(',', getSess()['sub_role_id']);
			array_push($role, getSess()['role_id']);

			// 控制操作按钮
			if(isset($_GET['is_audit']) && isset($_GET['node']) && isset($_GET['state'])){
			
				// 当前操作为审核，若成果状态正确方可操作审核和保存				
				$data['can_audit'] = CommonWhether::Not[XPHEnum::Value];
				if($data['detail']['status']!=ResultState::Auditing[XPHEnum::Value]){
					if(in_array(WebRole::Sscientifictaff[XPHEnum::Value], $role)){
						$data['can_save']=CommonWhether::Whether[XPHEnum::Value];
						$data['can_pass']=CommonWhether::Not[XPHEnum::Value];
						$data['can_refused']=CommonWhether::Not[XPHEnum::Value];
					}else{
						$data['can_save']=CommonWhether::Not[XPHEnum::Value];
						$data['can_pass']=CommonWhether::Not[XPHEnum::Value];
						$data['can_refused']=CommonWhether::Not[XPHEnum::Value];
					}
				}else{					
					if(in_array(WebRole::BranchManage[XPHEnum::Value], $role) && $_GET['node']==AuditNode::Second[XPHEnum::Value] || $_GET['state'] == AuditState::Pass[XPHEnum::Value]){
						$data['can_save']=CommonWhether::Not[XPHEnum::Value];
						$data['can_pass']=CommonWhether::Not[XPHEnum::Value];
						$data['can_refused']=CommonWhether::Not[XPHEnum::Value];
					}else{
						$data['can_save']=CommonWhether::Whether[XPHEnum::Value];
						$data['can_pass']=CommonWhether::Whether[XPHEnum::Value];
						$data['can_refused']=CommonWhether::Whether[XPHEnum::Value];
					}	
				}
			}else{
				$data['can_pass']=CommonWhether::Not[XPHEnum::Value];
				$data['can_refused']=CommonWhether::Not[XPHEnum::Value];
				// 当前操作为成果人，若成果状态正确方可保存提交
				if($data['detail']['status']==ResultState::UnSubmit[XPHEnum::Value] || $data['detail']['status']==ResultState::Fail[XPHEnum::Value]){
					$data['can_save']=CommonWhether::Whether[XPHEnum::Value];
					$data['can_audit']=CommonWhether::Not[XPHEnum::Value];
				}else{
					if (in_array(WebRole::Admin[XPHEnum::Value], $role)) {
                        $data['can_save']=CommonWhether::Whether[XPHEnum::Value];
                    }else{
                        $data['can_save']=CommonWhether::Not[XPHEnum::Value];
                    }
					$data['can_audit']=CommonWhether::Not[XPHEnum::Value];
				}
			}
			

		}


		$this -> load -> view('admin/monographEdit',$data);

	}



	function save(){
		
		$param = $_POST;$save_type = $_POST['save_type'];unset($param['img']);unset($param['files']);unset($param['save_type']);
		unset($param['identity']);unset($param['author_name']);unset($param['author_id']);

		

		if(!isset($_POST['type']) || $_POST['type']=="-1"){
        	 exit(retJson('请选择著作类别',false));
        } 

        if(!isset($_POST['subject']) || $_POST['subject']=="-1"){
        	 exit(retJson('请选择学科门类',false));
        } 
	

        if(!isset($_POST['identity']) || $_POST['identity']=="-1"){
        	 exit(retJson('请选择教师/学生/外校老师',false));
        } 

        
		if(!isset($_POST['dept_name']) || $_POST['dept_name']=="-1"){
        	 exit(retJson('请所属部门',false));
        }

		if (!isset($_POST['examine_level']) || $_POST['examine_level']=="-1") {
            exit(retJson('请选择等级', false));
        }

		if (!isset($_POST['is_submit_cg']) || $_POST['is_submit_cg']=="-1") {
            exit(retJson('请选择是否提交科研奖励', false));
        }

		if(!isset($_POST['is_cooperation']) || $_POST['is_cooperation']=="-1"){
        	$param['is_cooperation'] = null;
        }
        
       //上传图片
		if(!isset($_POST['img']) || $_POST['img'] == ''){
			$param1=array();
		}else{

			/*$_POST['img']=$this->NOTXSS_POST['img'];
	     	//处理img
	        if(checkStringIsBase64($_POST['img'])){
	            $checkRet = uploadImg($_POST['img'],'paperImg');
	            if(!$checkRet['status']){
	                exit(toRetJson($checkRet));
	            }
	            $param1['src'] = $checkRet["v"];
	        }else{      
	            $param1['src'] = $_POST['img'];        
	        } 

	        $param1['type'] = ResultsType::Second[XPHEnum::Value];			
      	    $param1['file_type'] = FileType::Img[XPHEnum::Value];
      	    $param1['status'] = CommonStatus::UnDeleted [XPHEnum::Value];       
	        $param1['created'] = time();*/

      		foreach ($_POST['img'] as $k => $v) {
      			$param1[$k]['data_id']=$param['id'];
      			$param1[$k]['src']=$v;
      			$param1[$k]['type'] = ResultsType::Second[XPHEnum::Value];			
    	      	$param1[$k]['file_type'] = FileType::Img[XPHEnum::Value];
    	      	$param1[$k]['status'] = CommonStatus::UnDeleted [XPHEnum::Value];       
    		    $param1[$k]['created'] = time();
      		}

		}

		//上传文件

		if(!isset($_POST['files'])|| $_POST['files'] == ''){
			$param2=array();
		}else{		
			foreach ($_POST['files'] as $k => $v) {	
				$param2[$k]['data_id'] = $param['id'];
				$param2[$k]['src'] = $v;        
				$param2[$k]['type'] = ResultsType::Second[XPHEnum::Value];
	      	    $param2[$k]['file_type'] = FileType::File[XPHEnum::Value];
	      	    $param2[$k]['status'] = CommonStatus::UnDeleted [XPHEnum::Value];       
		        $param2[$k]['created'] = time();
		    }
		}
		// 成果人信息
		foreach ($_POST['identity'] as $k => $v) {
			if($_POST['identity'][$k]=='-1'){
				exit(retJson('请选择教师/学生/外校老师',false));
			}
			if($_POST['author_name'][$k]==''){
				exit(retJson('请输教师/学生/外校老师姓名',false));
			}
			$author[$k]['data_id']=$param['id'];
			$author[$k]['type']=ResultsType::Second[XPHEnum::Value];
			$author[$k]['identity']=$_POST['identity'][$k];
			$author[$k]['author_id']=$_POST['author_id'][$k];
			$author[$k]['author_name']=$_POST['author_name'][$k];
			$author[$k]['created']=time();
		}

		  //获取32位随机编码
		  $get_only_code = $this->check_service->set_only_code(ResultsType::Second[XPHEnum::Value],$_POST);

		if($param['id'] == '0'){
			$names = $this -> Monograph_model -> get_single(array('name'=>$param['name'],'is_del'=>CommonWhether::Not [XPHEnum::Value]));
			if($names){
	 			exit(retJson('著作名称已存在相同的，请注意',false));
			}

			$lls = $this -> Monograph_model -> get_single(array('only_code'=> $get_only_code,'is_del'=>CommonWhether::Not [XPHEnum::Value]));
            if($lls){ //如果存在相同则重新获取32位编码
                $get_only_code = $this->check_service->set_only_code(ResultsType::Second[XPHEnum::Value],$_POST);
            }
		
			unset($param['id']);
			//添加
			$param['publish_time'] = strtotime($param['publish_time']);
			$param['is_del'] = CommonWhether::Not [XPHEnum::Value];
			$param['creator'] = getSess()['id'];			
			$param['created'] = time();
			$param['status'] = ResultState::UnSubmit[XPHEnum::Value];//成果状态
			$param['only_code'] = $get_only_code;
			 //pri($param1);
			
			$id = $this -> Monograph_model -> add($param);

			/*//保存图片
			$param1['data_id'] = $id;	
	         $this -> File_model -> add($param1);

			$param2['data_id'] = $id;
             $this -> File_model -> add($param2);*/

 			foreach ($param1 as $k => $v) {
				$param1[$k]['data_id'] = $id;
 				$this -> File_model -> add($param1[$k]);
 			}
 			foreach ($param2 as $k => $v) {
 				$param2[$k]['data_id'] = $id;
 				$this -> File_model -> add($param2[$k]);
 			}

 			// 保存作者
 			foreach ($author as $k => $v) {
 				$author[$k]['data_id']=$id;
 				$this->Author_model->add($author[$k]);
 			}
             //提交的时候新增审核记录
			if($save_type  == 2){
 			    $ress = $this->audit_service->addAudit(ResultsType::Second[XPHEnum::Value],$id);
 			 	
			}

			exit(retJson("添加成功.", true));

		}else{
			
			//修改	
			$param['only_code'] = $get_only_code;
			$param['publish_time'] = strtotime($param['publish_time']);
			$this -> Monograph_model -> update($param);

			/*$imglist = $this -> File_model -> get_single(array("data_id" => $param['id'],'type'=>ResultsType::Second[XPHEnum::Value],'file_type'=>FileType::Img[XPHEnum::Value]));
			if($imglist){
				//修改图片地址
				 $sql = "UPDATE `db_file` SET `src` = '".$param1['src']."'  WHERE data_id=".$param['id']." and type=".ResultsType::Second[XPHEnum::Value]." and file_type=".FileType::Img[XPHEnum::Value].";";
				 $res = $this -> db ->query($sql);
			}else{
				//保存图片
				$param1['data_id'] =$param['id'];	
	        	 $this -> File_model -> add($param1);

			}

			$filelist = $this -> File_model -> get_single(array("data_id" => $param['id'],'type'=>ResultsType::Second[XPHEnum::Value],'file_type'=>FileType::File[XPHEnum::Value]));
			if($filelist){
					//修改文件地址
				 $sql1 = "UPDATE `db_file` SET `src` = '".$param2['src']."'  WHERE data_id=".$param['id']." and type=".ResultsType::Second[XPHEnum::Value]." and file_type=".FileType::File[XPHEnum::Value].";";
				  $res1 = $this -> db ->query($sql1);
			}else{
				$param2['data_id'] = $param['id'];
	             $this -> File_model -> add($param2);

			}*/

			// 删除原有图片
			$this->File_model->delBatch($this->sqlEscape(" type=?? and data_id=?? and file_type=??",array(ResultsType::Second[XPHEnum::Value],$param['id'],FileType::Img[XPHEnum::Value])));
			// 新增新图片
			foreach ($param1 as $k => $v) {
				$this -> File_model -> add($v);
			}
			// 删除原有文件
			$this->File_model->delBatch($this->sqlEscape(" type=?? and data_id=?? and file_type=??",array(ResultsType::Second[XPHEnum::Value],$param['id'],FileType::File[XPHEnum::Value])));
			// 新增新文件
			foreach ($param2 as $k => $v) {				
				$this -> File_model -> add($v);
			}

			// 删除原有作者
			$this->Author_model->delBatch($this->sqlEscape(" type=?? and data_id=??",array(ResultsType::Second[XPHEnum::Value],$param['id'])));
			// 新增新作者
			foreach ($author as $k => $v) {
				$this->Author_model->add($v);
			}

			
            //当状态已经审核通过后为已公开的时候,同步修改考核库的数据
            if($param['status'] ==  ResultState::Publiced[XPHEnum::Value]){
                $host_url = headerurl()."/"."zjipc_kycg/";
                $connar['join'][0]=array('(select group_concat(db_author.author_name  ORDER BY db_author.id ASC) author,group_concat( db_user.usercode ORDER BY db_author.id ASC ) authorcode,group_concat(db_author.identity  ORDER BY db_author.id ASC) identity,data_id FROM db_author left join db_user on db_user.id = db_author.author_id and db_user.username=db_author.author_name WHERE db_author.type = '.ResultsType::Second[XPHEnum::Value].'  and db_user.is_del=0 GROUP BY db_author.data_id ) author','author.data_id=db_monograph.id');
				$connar['join'][1]=array('(select group_concat(db_file.src ORDER BY db_file.id ASC separator \',\' ) AS imgurl, db_file.data_id AS img_data_id FROM db_file	WHERE ((db_file.type = '.ResultsType::Second[XPHEnum::Value].' ) AND (db_file.file_type = '.FileType::Img[XPHEnum::Value].' )) GROUP BY db_file.data_id) img_view','img_view.img_data_id=db_monograph.id');
				$connar['join'][2]=array('(select CONCAT(\''.$host_url .'\',group_concat(db_file.src ORDER BY db_file.id ASC SEPARATOR \','.$host_url.'\' )) AS fileurl, db_file.data_id AS file_data_id FROM db_file	WHERE ((db_file.type = '.ResultsType::Second[XPHEnum::Value].' ) AND (db_file.file_type = '.FileType::File[XPHEnum::Value].')) GROUP BY db_file.data_id) file_view','file_view.file_data_id=db_monograph.id');
				$connar['where'] = $this->sqlEscape('db_monograph.id=?? ', array($param['id']));
				$data=$this->Monograph_model->get_single_full($connar);
                $connar1['where'] = $this->sqlEscape('uuid=?? ', array('zz_'.$param['id']));
                $kh = $this->Monograph_kh_model->get_single_full($connar1);
                if($kh){
                    unset($data['id']); unset($data['is_submit_kh']);unset($data['is_submit_cg']);unset($data['data_id']);unset($data['img_data_id']); unset($data['file_data_id']);  //移除考核表中不存在的字段
                    $data['id'] =$kh['id']; 
					$data['publish_time'] = date("Y-m-d",$data['publish_time']);
					$data['created'] = date("Y-m-d",$data['created']);
                    $this -> load -> model("Admin_model");
                    $admin = $this-> Admin_model -> get_single(array('id'=>$data['creator']));
                    $data['creator'] = $admin['username'];
                    $this->Monograph_kh_model->update($data,'id'); //修改考核库
                }
               
            }

             //提交的时候新增审核记录
			if($save_type  == 2){
 			    $ress = $this->audit_service->addAudit(ResultsType::Second[XPHEnum::Value], $param['id']);
 			 	
			}

			  exit(retJson("修改成功.", true));	
		}
			
	}

	

	//删除

	function delete($id){
		$list = $this -> Monograph_model -> get_single(array("id" => $id));
		if($list){
			$param['id'] = $id;
			$param['is_del'] = CommonWhether::Whether [XPHEnum::Value];//已删除
			$this -> Monograph_model -> update($param);
			$connar1['where'] = $this->sqlEscape('uuid=?? ', array('zz_'.$id));
            $kh = $this->Monograph_kh_model->get_single_full($connar1);
            if($kh){
                $this->Monograph_kh_model->update(array('id'=>$kh['id'],'is_del'=>CommonWhether::Whether[XPHEnum::Value]));
            }
		}
			exit(retJson("删除成功.", true));
			
	}


		//提交审核
	
	function submit_audit($id){

		 $ress = $this->audit_service->addAudit(ResultsType::Second[XPHEnum::Value],$id);

		 if($ress['status'] == true){

		 	  exit(retJson("操作成功.", true));	
		 }		

	}

	// 审核列表
	function auditView($id){
		$data['audit']=$this->audit_service->auditProcess(ResultsType::Second[XPHEnum::Value],$id);
		$this->load->view('admin/auditView',$data);
	}


		//获取刊物级别
	function getPublisherLevel(){
		$publish_house = $_POST['publish_house'];
		$list = $this -> Publisher_model -> get_single(array("name" => $publish_house,"type"=>PublisherLevel::First[XPHEnum::Value]));
		if(!$list){
			$list = $this -> Publisher_model -> get_single(array("name" => $publish_house,"type"=>PublisherLevel::Second[XPHEnum::Value]));		
		}

		if(!$list){
			$data['type'] = PublisherLevel::Third[XPHEnum::Caption];

		}else{
			$data['type'] =  (new PublisherLevel())->show($list['type']);
		}		
		echo json_encode($data);

	}


	public function importExcel()
	{
        if (!empty($_FILES)) {
            $pathlist  = $this->upload_service->UploadFile('monograph', true); //上传文件
            $excellist = $this->export_service->importexcel($pathlist, 'V', 'B', 3);

            $errer = array();
            foreach ($excellist as $key => $value) {
				$type = $value['D']=='教师' ? CommonIdentity::Teacher[XPHEnum::Value] : CommonIdentity::Student[XPHEnum::Value];
				$author = $this->User_model->get_single(array('username' => $value['C'], 'type' => $type));

                if (isset($author)) {
					$param = array(
						'name'                => $value['B'],
						// 'author'              => $value['C'],
						// 'identity'            => $value['D'],
						'words_number'        => $value['E'],
						'school_words_number' => $value['F'],
						'type'                => $value['G'],
						'nature'              => $value['H'],
						'publish_time'        => PHPExcel_Shared_Date::ExcelToPHP($value['I']),
						'publish_house'       => $value['J'],
						'publish_house_level' => $value['K'],
						'publish_address'     => $value['L'],
						'isbn'                => $value['M'],
						'subject'             => $value['N'],
						'is_cooperation'      => $value['O']=='否' ? CommonWhether::Not[XPHEnum::Value] : CommonWhether::Whether[XPHEnum::Value],
						'school_rank'         => $value['P'],
						'personal_rank'       => $value['Q'],
						'performance_score'   => $value['R'],
						'bonus'               => $value['S'],
						'dept_name'           => $value['T'],
						'remark'              => $value['U'],
						'award_year'          => $value['V'],
						'created'             => time(),
						'creator'             => getSess()['id'],
						'status'              => ResultState::Publiced[XPHEnum::Value],
						'is_del'              => CommonWhether::Not[XPHEnum::Value],
                	);
					$id = $this->Monograph_model->add($param);
					$param1 = array(
						'type'        => ResultsType::Second[XPHEnum::Value],
						'data_id'     => $id,
						'identity'    => $type,
						'author_id'   => $author['id'],
						'author_name' => $value['C'],
						'created'     => time(),
					);
                    $this->Author_model->add($param1);
                }else{
					$errer[] =  $key + 1;
				}
            }
			exit(retJson("导入成功", true, $errer));
        } else{
            exit(retJson("导入失败", false));
		}
	}

	
    //提交考核库

    // public function submit_kh($id){
    //     $ress = $this->check_service->addCheckDetail(ResultsType::Second[XPHEnum::Value], $id);

    //     if ($ress['status'] == true) {
    //         exit(retJson("操作成功.", true));
    //     }
    // }


}